package com.zzr.demo.redis.service.impl;

import com.zzr.demo.redis.service.RecorderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

/**
 * @author: xiaomi
 * @date: 2021/10/10
 * @description: 用户行为记录器
 */
@Service
@Slf4j
public class ActionRecorderServiceImpl implements RecorderService {

    final String RECORDER_BITMAP_KEY = "recorder::bitmap";
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public void recordUser(long userId) {
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        //SETBIT 把用户ID 作为偏移量
        Boolean aBoolean = opsForValue.setBit(RECORDER_BITMAP_KEY, userId, true);
        //NOTEME aBoolean 返回了 false 说明了旧值是 0，只要不是 null 那么设置就是成功的！
        log.info("userId:{},setbit :{}", userId, aBoolean);
    }

    @Override
    public long countRecord() {
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        Long bitCount = stringRedisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection redisConnection) throws DataAccessException {
                return redisConnection.bitCount(RECORDER_BITMAP_KEY.getBytes());
            }
        });
        
        log.info("bitCount:{}", bitCount);
        return bitCount;
    }
}
